<script setup>
import {
    Position,
    Handle,
    useNode,
    useVueFlow
} from '@vue-flow/core'
import {
    ref,
    watch,
    onMounted,
    computed,
    onUnmounted,
    inject
} from "vue";
import {
    NInput
} from 'naive-ui';
import {
    useMessage
} from "naive-ui";
import {
    getNodeOutputFieldNames
} from '../node-def'

import IntentionEditDrawer from './cnps/IntentionEditDrawer.vue';

const message = useMessage();
const props = defineProps(['id', 'data'])
const flow = useVueFlow();
const showEditDrawer = ref(false);
//空的意图对象
const emptyIntention = {
    key: "",
    description: "",
    cases: ['']
};

/** 获取所有前置节点的输出字段，并生成下拉选项 */
const prevOutputFieldOptions = ref([])


watch(() => flow.getEdges.value, (newV) => {
    console.debug("监听到edge改动", newV)
    updatePrevOutputFieldOptions(props.id);
})
//监听prevOutputFieldOptions
watch(() => prevOutputFieldOptions.value, (newV) => {
    //如果数组是空值,则清空input的值
    if (newV.length === 0) {
        // inputField.value = null;
        props.data.intentionConfig.inputField = null;
    }
})
flow.onEdgesChange(events => {
    console.debug("intention init", events)
    if (events.some(item => item.type === 'remove' || item.type === 'add')) {
        prevOutputFieldOptions.value = [];
        updatePrevOutputFieldOptions(props.id);
    }
})

function updatePrevOutputFieldOptions(sourceNodeId) {
    const connections = flow.getConnectedEdges(sourceNodeId).filter(edge => edge.targetNode.id == sourceNodeId);
    console.log(connections, "connections")
    // 遍历所有前置连接
    connections.forEach(connection => {
        const sourceNode = connection.sourceNode;
        if (sourceNode) {
            // 获取该类型节点的所有输出字段名称
            const outputFields = getNodeOutputFieldNames(sourceNode.type);

            // 从sourceNode.data中获取对应字段的值
            outputFields.forEach(fieldPath => {
                // 处理嵌套字段路径，如 "llmConfig.outputField"
                const value = fieldPath.split('.').reduce((obj, key) => obj && obj[key], sourceNode
                    .data);
                if (value) {
                    if (prevOutputFieldOptions.value.some(item => item.value === value) == false) {
                        prevOutputFieldOptions.value.push({
                            label: value,
                            value: value
                        });
                    }
                }
            });
            console.log(prevOutputFieldOptions.value, "意图识别的的问题数组")
            updatePrevOutputFieldOptions(connection.source)

        }
    });

}

/** 获取所有前置节点的输出字段，并生成下拉选项 */




// 关闭抽屉--添加意图
function handleDrawerAddYesClick({
                                     componentRef,
                                     close
                                 }) {
    componentRef.submit((data) => {
        //判断 data中的key跟描述不能为空值
        if (!validateData(data)) {
            return;
        }
        //检查key值是否重复
        const intentions = props.data.intentionConfig.intentions;
        // 检查除当前意图外是否有重复的key
        for (let i = 0; i < intentions.length; i++) {
            if (intentions[i].key === data.value.key.trim()) {
                message.error('该 Key 已存在，请使用其他 Key');
                return;
            }
        }
        console.debug("新增意图", data.value)
        props.data.intentionConfig.intentions.push(data.value);
        close();
    })
}

// 关闭编辑抽屉--修改意图
function handleDrawerUpdateYesClick({
                                        componentRef,
                                        close
                                    }) {

    componentRef.submit((data, index) => {
        //判断 data中的key跟描述不能为空值
        if (!validateData(data)) {
            return;
        }
        //检查key值是否重复
        const intentions = props.data.intentionConfig.intentions;
        // 检查除当前意图外是否有重复的key
        for (let i = 0; i < intentions.length; i++) {
            if (i !== index && intentions[i].key === data.value.key.trim()) {
                message.error('该 Key 已存在，请使用其他 Key');
                return;
            }
        }


        console.debug("修改意图", data.value)
        props.data.intentionConfig.intentions[index] = data.value;
        close();
    })
}

//检验值
function validateData(data) {
    // 判断 data中的key跟描述不能为空值
    if (data.value.key.trim() === '') {
        message.error('Key不能为空');
        return false;
    }
    if (data.value.description.trim() === '') {
        message.error('描述不能为空');
        return false;
    }

    // 案例数组中也不能为空
    if (data.value.cases.length === 0) {
        message.error('案例不能为空');
        return false;
    }
    for (let i = 0; i < data.value.cases.length; i++) {
        if (data.value.cases[i].trim() === '') {
            message.error('案例不能为空');
            return false;
        }
    }


    return true;
}


const updateNodesData = inject("updateNodesData")
// 监听props.data的变化
watch(() => props.data, (newValue, oldValue) => {
    console.log('props.data changed ', newValue);
    updateNodesData();
}, {
    deep: true
})


// 删除意图
const removeIntention = (index) => {
    const intention = props.data.intentionConfig.intentions[index];
    //移除连线
    flow.removeEdges((edges) => {
        console.debug("移除意图识别的连线", edges);
        return edges.filter(edge => edge.source == props.id && edge.sourceHandle == intention.key);
    })
    props.data.intentionConfig.intentions.splice(index, 1);


};
//计算链接点的位置
const intentionRef = ref(null); // 引用意图识别组件的容器


onMounted(() => {
    updatePrevOutputFieldOptions(props.id); //1.初始化的修改数组
});


</script>

<template>
    <div class="_container" ref="intentionRef">
        <div class="fx fx-c_center pad-16 header">
            <div class="fx fx-center wh-40 logo">
                <jb-icon :local="true" icon="gravity-ui:display-pulse" width="30" color="#22c55e"></jb-icon>
            </div>
            <div class="ml-10 tc-dark">
                <div>意图识别</div>
                <p class="font-12 tc-assist">由AI 根据用户提问,识别用户意图</p>
            </div>
        </div>
        <div class="form fx-col pad-16 intention-box-div" @mousedown.stop>

            <label>问题</label>
            <n-select placeholder="请选择问题" clearable v-model:value="props.data.intentionConfig.inputField"
                      :options="prevOutputFieldOptions"></n-select>
            <!-- 意图数组 -->
            <label>意图</label>
            <div v-for="(intention, index) in props.data.intentionConfig.intentions" :key="intention.id"
                 class="intention-item flex justify-between items-end">
                <div class="flex-col items-start flex-1 overflow-hidden">
                    <n-popover trigger="hover" style="max-width: 200px;">
                        <template #trigger>
                            <div class="ellipsis max-w-full cursor-pointer">
                                <b class="mr-2">{{ intention.key }}</b>
                                {{ intention.description }}
                            </div>
                        </template>
                        <span>{{ intention.description }}</span>
                    </n-popover>
                    <n-popover trigger="hover" style="max-width: 200px">
                        <template #trigger>
                            <div class="ellipsis  max-w-full  cursor-pointer text-gray-500">
                                {{ intention.cases.join('; ') }}
                            </div>
                        </template>
                        <span>{{ intention.cases.join('; ') }}</span>
                    </n-popover>
                </div>
                <div class="shrink-0 ml-4">
                    <jb-btn text size="small" drawerTitle="编辑意图" icon=" " type="primary" ghost
                            :drawerComponent="IntentionEditDrawer" :drawerComponentProps="{show:showEditDrawer,data: props.data,
            intention: props.data.intentionConfig.intentions[index],
            index: index}" :drawerArgs="{width: '500px',maskClosable:false}" @drawerYesClick="handleDrawerUpdateYesClick">
                        <jb-icon icon="ant-design:edit-filled" :local="true"></jb-icon>
                    </jb-btn>&nbsp;
                    <jb-btn text strong ghost type="error" size="small" icon="ri:delete-bin-line"
                            @click="removeIntention(index)">
                    </jb-btn>

                </div>


            </div>

            <div key="INNER_NO_MATCH" class="intention-item no-match flex justify-center items-center">
                <b class="text-gray-500">未匹配任何意图</b>
            </div>
            <div class="w-full">
                <jb-btn style="width: 470px;" drawerTitle="添加意图" type="success" :drawerComponent="IntentionEditDrawer"
                        :drawerComponentProps="{show:showEditDrawer,data: props.data,
                intention: emptyIntention,index: 0}" :drawerArgs="{width: '500px',maskClosable:false}"
                        @drawerYesClick="handleDrawerAddYesClick"> 添加意图
                </jb-btn>
            </div>
            <label>AI 模型</label>
            <jb-select url="aiResource/listAllEnabledType" labelField="name" placeholder="请选择AI模型" valueField="sn"
                       v-model:value="props.data.llmConfig.modelType"></jb-select>


        </div>
        <div class="footer pad-16">
            <p class="tc-gray ">输出字段</p>
            <div class="output mt-8 pad-8 fx fx-c_center fx-m_between">
                <div class="fx fx-c_center">
                    <div class="output-flag noshrink"></div>
                    <n-input v-model:value="props.data.intentionConfig.outputField" placeholder="字段名"
                             class="tc-gray ml-8 w-120"></n-input>
                </div>
                <span class="tc-assist">AI生成的回答</span>
            </div>
        </div>

        <Handle type="target" :position="Position.Left"/>

        <Handle type="source" id="fail" :position="Position.Right"
                style="top: 140px"/>
        <div v-for="(item,index) in props.data.intentionConfig.intentions" :key="item.id">
            <Handle type="source" :id="item.key" :position="Position.Right" :style="{top: `${248 + 68*index}px`}" class="intention"/>
        </div>

        <Handle type="source" id="INNER_NO_MATCH" class="intention"
                :position="Position.Right" style="top:initial;bottom: 275px;"/>


    </div>
</template>

<style scoped>
._container {
    position: relative;
    /* 确保父容器有定位属性 */
    background-color: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    box-sizing: border-box;
    width: 500px;
    box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.1) 0px 4px 6px -4px;
}

.header,
.form {
    border-bottom: 1px solid rgb(229, 231, 235);
}

.logo {
    background: #dcfce7;
    border-radius: 12px;
}

label {
    margin-bottom: 8px;
}

label:not(:first-child) {
    margin-top: 16px;
}

.output {
    background: rgb(249, 250, 251);
    border-radius: 12px;
}

.output-flag {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #22c55e;
}


.intention-item {
    background-color: rgba(240, 173, 78, 0.04);
    border: 1px solid rgba(240, 173, 78, 0.16);
    padding: 8px 16px;
    height: 60px;
    box-sizing: border-box;
    margin-bottom: 8px;
    border-radius: 4px;
    position: relative;
}

.intention-item.no-match {
    background-color: rgba(121, 121, 121, 0.05);
}

.no-match :deep(n-empty__description) {
    font-size: 12px;
}

.intention-display {
    display: flex;
    flex-direction: column;
    cursor: pointer;
}

</style>